//
//  YSZOauthViewController.swift
//  swiftweibo6
//
//  Created by ysz on 15/11/24.
//  Copyright © 2015年 user. All rights reserved.
//

import UIKit

import SVProgressHUD

class YSZOauthViewController: UIViewController {

    override func loadView() {
        view = webView
        webView.delegate = self
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //加载授权页面
        let request = NSURLRequest(URL: YSZNetworkTools.shardInsatance.oauthURL())
        webView.loadRequest(request)
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
    }
    //填充帐号
    func autoFill()
    {
        let js = "document.getElementById('userId').value='314736131@qq.com'; document.getElementById('passwd').value='123456789';"
        //执行js 代码
        webView.stringByEvaluatingJavaScriptFromString(js)
    }
    //加载accessToken
    func loadAccessToken(code: String)
    {
        //发送网路请求
        YSZNetworkTools.shardInsatance.loadAccessToken(code) { (result, error) -> () in
            //判断是否有错误
            if error != nil || result == nil
            {
                print("error=\(error)")
                print("result=\(result)")
                SVProgressHUD.showErrorWithStatus("你的网络不给力", maskType: SVProgressHUDMaskType.Black)
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.close()
                    
                })
                return
            }
            //保存
            let userAccount = YSZUserAccount(dict: result!)
            userAccount.saveAccount()
            print("userAccount: \(userAccount)")
            self.close()
            AppDelegate.switchRootViewController(false)
        }
    
    }
    //关闭控制器
    func close()
    {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }

    private lazy var webView = UIWebView()
}

extension YSZOauthViewController: UIWebViewDelegate
{
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("正在加载", maskType: SVProgressHUDMaskType.Black)
        
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    // webView加载链接,每当webView加载一个链接都会通过这个代理方法来询问我们这个地址是否可以加载 true表示可以加载, false 就不加载.
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        let urlstring = request.URL!.absoluteString
        print("url:\(urlstring)")
        //当用户点击取消或同意,拦截,不让它加载,我们来处理
        if !urlstring.hasPrefix(YSZNetworkTools.shardInsatance.redirect_uri)
        {
            return true
        }
        
        //点击取消 或 点击授权
        if let query = request.URL?.query
        {
            let codestring="code="
            //判断是否时code开头
            if query.hasPrefix(codestring)
            {
                let nsquery = query as NSString
                let code = nsquery.substringFromIndex(codestring.characters.count)
                print("code1:\(code)")
                loadAccessToken(code)
                
            }
            else
            {
                close()
                return false
            }
            
        }
        return false
    }
}



